<?php
header('Content-type: text/html; charset=utf-8');
$servername = "localhost";
$username   = "root";
$password   = "";
$dbname = "PHPlesson";

// 创建连接
$conn = mysql_connect($servername, $username, $password);

// 检测连接
if (!$conn) {
    die("Connection failed: " . mysql_connect_error());
} else {
    mysql_select_db($dbname, $conn);
    mysql_query("SET NAMES 'utf8'");
    // 下面将点赞数据写入表中
    $num = $_REQUEST['num'];
    $creator = $_REQUEST['creator'] ? $_REQUEST['creator'] : $username;
    $thumbUpTime = date('Y-m-d H:i:s');
    $sql = "SELECT `creator`, `num` FROM `thumbup` WHERE `creator` like '$creator'";

    $result = mysql_query($sql, $conn);
    $arr = array();
    while ($row = mysql_fetch_array($result)) {
        array_push($arr, array('creator' => $row['creator'], 'num' => $row['num']));
    }
    if (count($arr)) {
        $currNum = ++$arr[0]['num'];
        $sql = "UPDATE `thumbup` SET `num`='$currNum',`thumbUpTime`='$thumbUpTime' WHERE `creator`like'$creator'";
    } else {
        $sql = "INSERT INTO `thumbup`(`creator`, `num`, `thumbUpTime`) VALUES ('$creator', '$num', '$thumbUpTime')";
    }
    
    $result = mysql_query($sql, $conn);
    if ($result) {
        $result = array('resutlCode' => 0, 'resultMsg' => "点赞成功！");
    } else {
        $result = array('resutlCode' => 1, 'resultMsg' => "Error: " . $sql . "<br>" . mysql_error($conn));
    }
    echo json_encode($result);
}
?>
